import React from 'react';
import {
  Row,
  Col,
  Icon,
  Card,
  Timeline,
  notification,
  AutoComplete,
  Table,
  Switch,
  DatePicker,
  Select
} from 'antd';
import CountUp from 'react-countup';
import classnames from 'classnames';
import axios from 'axios';
import intercept from '../../utils/intercept';
import { config } from 'utils';
import './less/common.less';
const Option = AutoComplete.Option;
const { RangePicker } = DatePicker;
const OptionSelect = Select.Option;
export default class StationInfo extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      stationinfo: '',
      keyword: '',
      stations: [],
      daysells: [],
      opTerminals: [],
      switchstate: false,
    };
  };
  componentDidMount() {
    this.getStationInfo('410101');
  };
  search = (value) => {
    this.setState({ keyword: value });
    this.getStationInfo(value);
  }
  getStationInfo = (globalcode) => {
    const token = sessionStorage.getItem("token");
    axios
      .get(`${config.api}DailyStatics/GetStationInfo?globalcode=${globalcode}`, {
        headers: {
          Authorization: 'Bearer ' + token
        }
      })
      .then((res) => {
        // console.log(res.data);
        if (res.data.result) {
          let tmp = res
            .data
            .stationsInfo
            .map(m => (
              <Option key={m.key} value={m.label}>
                <span>{m.label}</span>
              </Option>
            ));
          let statetmp = res.data.stationInfo.isAllow === 1 ? true : false;
          this.globalCode = res.data.stationInfo.globalcode;
          let machinecodes = this.machinecodes == undefined ? '' : this.machinecodes;
          let datestr = this.datestr == undefined ? '' : this.datestr;
          this.GetAtmSaleInfo(this.globalCode, machinecodes, datestr)
          this.setState({ stationinfo: res.data.stationInfo, stations: tmp, daysells: res.data.daySells, switchstate: statetmp })
        } else {
          this.openNotification('获取车站信息失败', res.data.errorMessage, 'red');
          this.setState({ stations: res.data.stations })
        }
      })
      .catch(err => {
        intercept;
      })
      .then(() => {
        axios.get(`${config.api}CustomService/GetTerminalInfo?globalCode=${this.globalCode}`, {
          headers: {
            Authorization: 'Bearer ' + token
          }
        })
          .then((data) => {
            // console.log(data)
            let opTerminals = data.data.terminals.map((item, i) => (<OptionSelect key={i} value={item.machineCode}>
              <span>{item.machineCode}</span>
            </OptionSelect>))
            this.setState({ opTerminals: opTerminals })
          })
          .catch(err => {
            intercept;
          })
      })
  }

  GetAtmSaleInfo = (globalCode, machinecodes, datestr) => {
    const token = sessionStorage.getItem("token");
    axios.get(`${config.api}CustomService/GetAtmSaleInfo?globalCode=${this.globalCode}&machinecodes=${machinecodes}&datestr=${datestr}`, {
      headers: {
        Authorization: 'Bearer ' + token
      }
    })
      .then((data) => {
        this.setState({ saleInfo: data.data.saleInfo })
      })
      .catch(err => {
        intercept;
      })
  }
  openNotification = (title, desc, color) => {
    notification.open({
      message: title, description: desc, icon: <Icon type="smile-circle" style={{
        color: color
      }} />
    });
  };
  switchChange = (checked, globalcode) => {
    let tmp = this.state.switchstate;
    const token = sessionStorage.getItem("token");
    let status = checked ? 1 : 0;
    let postdata = { globalCode: globalcode, status: status };
    axios.post(`${config.api}DailyStatics/EnableStation`, postdata, { headers: { Authorization: 'Bearer ' + token } }).then(res => {
      if (res.data.result) {
        this.openNotification("启用禁用车站", `${checked
          ? '开启'
          : '关闭'}车站售票成功`, "#108ee9");
        this.setState({ switchstate: !tmp });
      } else {
        this.openNotification("启用禁用车站", res.data.errorMessage, "red");
      }
    })
    .catch(err => {
      intercept;
    })
  }

  onChange = (date, dateString) => {
    let globalCode = this.globalCode == undefined ? '' : this.globalCode;
    let machinecodes = this.machinecodes == undefined ? '' : this.machinecodes;
    this.datestr = dateString;
    this.GetAtmSaleInfo(globalCode, machinecodes, dateString)
  }

  handleChange = (value) => {
    let globalCode = this.globalCode == undefined ? '' : this.globalCode;
    this.machinecodes = value;
    let datestr = this.datestr == undefined ? '' : this.datestr;
    this.GetAtmSaleInfo(globalCode, value, datestr)
  }

  render() {
    const figurecard = [
      {
        icon: 'book',
        title: '汽车票',
        number: 184,
        color: 'green',
        sub: 'Get More Space...',
        subIcon: 'info-circle'
      }, {
        icon: 'eye-o',
        title: '定制客运',
        number: 75,
        color: 'pink',
        sub: 'Google Analytics',
        subIcon: 'tag'
      }, {
        icon: 'bank',
        title: '城际约租',
        number: 3245,
        color: 'blue',
        sub: 'Last 24 Hours',
        subIcon: 'calendar'
      }
    ];
    const column = [
      {
        title: '日期',
        dataIndex: 'sellDate',
        width: 100
      }, {
        title: '分销商',
        dataIndex: 'traderAccount',
        width: 100
      }, {
        title: '售票数(张)',
        dataIndex: 'totalAmount',
        width: 100
      }, {
        title: '售票款(元)',
        dataIndex: 'totalMoney',
        width: 100
      }
    ];

    const saleInfoColumns = [
      {
        title: '日期',
        dataIndex: 'date',
      }, {
        title: '售票量',
        dataIndex: 'ticketAmount'
      }, {
        title: '售票金额',
        dataIndex: 'totalMoney'
      }
    ];

    const models = ['老接口', '新接口', '国标接口']
    return (
      <div>
        <div style={{
          textAlign: 'center',
          margin: 10
        }}>
          <AutoComplete
            style={{
              width: 600
            }}
            onSelect={this.search}
            dataSource={this.state.stations}
            optionLabelProp="value"
            filterOption={(inputValue, option) => option.props.children.props.children.toUpperCase().indexOf(inputValue.toUpperCase()) !== -1}
          />

        </div>
        <div>
          <Row gutter={16} className="showcase-1">
            {figurecard.map((v, k) => {
              return (
                <Col xs={24} sm={24} md={12} lg={6} xl={6} key={k}>
                  <Card
                    title={< div > <div
                      className={classnames('card-header', {
                        [`${v.color}`]: true
                      })}>
                      <h4><Icon type={v.icon} /></h4>
                    </div> < div className={
                      'card-content'
                    } > <p className={'category'}>{v.title}</p> < h3 > <CountUp
                      start={0}
                      end={v.number}
                      duration={2.75}
                      useEasing
                      useGrouping
                      separator="," /> </h3> </div > </div>}
                    bordered={false}
                    noHovering>
                    <div className={'card-footer'}>
                      <Icon type={v.subIcon} /> {' '}{v.sub}
                    </div>
                  </Card>
                </Col>
              )
            })
            }
          </Row>
        </div>
        <div
          style={{
            background: '#ECECEC',
            padding: '30px'
          }}>
          <Row gutter={16}>
            <Col span={6}>
              <Card title={this.state.stationinfo.shortname} bordered={false}>
                <Timeline>
                  <Timeline.Item>车站名称：{this.state.stationinfo.shortname}</Timeline.Item>
                  <Timeline.Item>接口类型：{models[this.state.stationinfo.model]}</Timeline.Item>
                  <Timeline.Item>是否售票： <Switch
                    checkedChildren="开"
                    unCheckedChildren="关"
                    onChange={(checked, globalcode) => {
                      this.switchChange(checked, this.state.stationinfo.globalcode)
                    }}
                    checked={this.state.switchstate} /></Timeline.Item>
                  <Timeline.Item>接口地址：{this.state.stationinfo.interfaceUrl}</Timeline.Item>
                  <Timeline.Item>车站编码：{this.state.stationinfo.globalcode}</Timeline.Item>
                  <Timeline.Item>车站地址：{this.state.stationinfo.address}</Timeline.Item>
                  <Timeline.Item>车站电话：{this.state.stationinfo.phones}</Timeline.Item>
                  <Timeline.Item>是否退票：{this.state.stationinfo.isRefund
                    ? '支持在线退票'
                    : '不支持在线退票'}</Timeline.Item>
                  <Timeline.Item>取票方式：{this.state.stationinfo.printtype}</Timeline.Item>
                </Timeline>
              </Card>
            </Col>
            <Col span={18}>
              <Card title="每日数据" bordered={false}>
                <Table
                  scroll={{ y: 300 }}
                  rowKey={record => record.key}
                  className='center'
                  columns={column}
                  dataSource={this.state.daysells}
                  // pagination={false}
                  loading={this.state.loading}
                  size="small" />
              </Card>
            </Col>
            <Col span={18} style={{ marginTop: 15 }}>
              <Select
                showSearch
                style={{ width: 200 }}
                placeholder="选择自助机"
                optionFilterProp="children"
                onChange={this.handleChange}
                filterOption={(input, option) => option.props.children.props.children.toUpperCase().indexOf(input.toUpperCase()) !== -1}
              >
                {this.state.opTerminals}
              </Select>
              <RangePicker style={{ marginLeft: 10 }} onChange={this.onChange} />
            </Col>
            <Col span={18} style={{ marginTop: 8 }}>
              <Card title="自助机售票情况" bordered={false}>
                <Table
                  style={{ height: '25vh' }}
                  rowKey={record => record.ticketAmount}
                  className='center'
                  columns={saleInfoColumns}
                  dataSource={this.state.saleInfo}
                  // pagination={false}
                  loading={this.state.loading}
                  size="small" />
              </Card>
            </Col>
          </Row>
        </div>
      </div>
    )
  }
}
